<template>
    <el-dialog v-model="dialogVisible" v-bind="props" class="my-dialog" @close="onClose">
        <slot></slot>
        <template #footer>
            <div class="my-dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button @click="confirm" type="primary" :loading="loading"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { DialogDefineProps, IDialogInstance } from './props';
const props = withDefaults(defineProps<DialogDefineProps>(), {
    title: '',
    destroyOnClose: true,
});

const dialogVisible = ref(false);
const loading = ref(false);

const open = () => {
    dialogVisible.value = true;
};

const close = () => {
    dialogVisible.value = false;
};

const cancel = async () => {
    dialogVisible.value = false;
};

const confirm = async () => {
    let result = true;
    loading.value = true;
    if (typeof props.onConfirm === 'function') {
        result = await props.onConfirm();
    }
    loading.value = false;
    if (result) {
        dialogVisible.value = false;
    }
};

const onClose = async () => {
    if (typeof props.onCancel === 'function') {
        await props.onCancel();
    }
};

defineExpose<IDialogInstance>({
    open,
    close,
});
</script>

<style scoped>
.my-dialog-footer {
    display: flex;
    width: 100%;
    justify-content: end;
}
</style>
